import { createStore, Store } from 'vuex'

//存储LocalStorage
const setLocalCartList=(state)=>{
  const {cartList}=state;
  const cartListString=JSON.stringify(cartList)
  localStorage.cartList=cartListString
}

// 获取LocalStorage
const getLocalCartList=()=>{
  try{
    return JSON.parse(localStorage.cartList)
  }catch(e){
    return {}
  }
}
export default createStore({
  state: {
    //数据格式：
    //shopId:{shopName:"",productList:{productId:{}}}
    // 详情数据：
     // //第一级是商品的id
      // shopId:{
      //   //第二层级是商品id
      //   // 第二层级内容是商品内容以及购物数量
      //   shopName:"沃尔玛",
      //   productList:{
      //     productId:{
      //       _id:'1',
      //       name: "番茄 250g / 份", 
      //       imgUrl: "http://www.dell-lee.com/imgs/vue3/tomato.png", 
      //       sales: 10, 
      //       price: 33.6,
      //       count:2
      //     }
      //   }
      // }
    cartList:getLocalCartList()
  },
  mutations: {
    changeCartItemInfo(state,payload){
      const {shopId,productId,productInfo,num}=payload;
      let shopInfo = state.cartList[shopId] || {shopName:'', productList:{}}
        console.log(shopInfo);
      let product=shopInfo.productList[productId]
      if(!product){
        productInfo.count=0
        product=productInfo
      }
      product.count=product.count+num
      if(num>0){product.check=true}
      if(product.count<0){product.count=0}
      shopInfo.productList[productId]=product
      state.cartList[shopId]=shopInfo
      setLocalCartList(state)
    },
    changeShopName(state,payload){
      const {shopId,shopName}=payload
      const shopInfo=state.cartList[shopId] || {
        shopName:'',
        productList:{}
      }
      shopInfo.shopName=shopName
      state.cartList[shopId]=shopInfo
      setLocalCartList(state)
    },
    changeCartItemCheck(state,payload){
      const{shopId,productId}=payload;
      const product =state.cartList[shopId].productList[productId]
      product.check=!product.check
      setLocalCartList(state)
    },
    cleanCartProducts(state,payload){
      const {shopId}=payload
      state.cartList[shopId].productList={}
      setLocalCartList(state)
    },
    setCartItemsChecked(state,payload){
      const {shopId}=payload
      const products = state.cartList[shopId].productList
      if(products){
        for(let key in products){
          const product=products[key]
          product.check=true
        }
      }
      setLocalCartList(state)
    },
    //提交或取消订单后将购物车清空
    clearCartData(state,shopId){
      state.cartList[shopId].productList = {}
    }
  },
  actions: {
  },
  modules: {
  }
})
